//
//  BKODAddressViewController.m
//  bestkeep
//
//  Created by 马乾征 on 16/12/7.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKODAddressViewController.h"
#import "Mediator+BKMy.h"
#import "BKODAddressCell.h"
#import "BK_OD_Color.h"
#import "BK_Adress_Tool.h"
NSString *const ODAddressList = @"deliver-address/list";


@interface BKODAddressViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    BKODAddressCellDelegate,
    BKODAddNewAddressCellDelegate
>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSArray <SectionModel *> *marr_Section;
@property(nonatomic, assign)NSInteger index;

@property(nonatomic, strong)ExceptionView *exceptionView;

@end

@implementation BKODAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setProperty];
    [self createUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self BK_ODAddress_getData_AddressList];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    NSArray *viewControllerArray = self.navigationController.viewControllers;
    if ([viewControllerArray.lastObject isKindOfClass:NSClassFromString(@"BK_Confirm_Order_VC")]) {
        NSIndexPath *indexPath = [_tableView indexPathForSelectedRow];
        if (indexPath) {
            [self backOrderViewController:indexPath];
        }
    }
    [BK_Adress_Tool BK_saveStr:@"None" withID:@"Add_Address_Success_and_Use"];
}

#pragma mark==================setProperty======================
-(void)setProperty{
    self.navigationItem.title = kOrderLocalizeString(@"BKOrderAddress");
    self.view.backgroundColor = ThemeBackgroundColor;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addAddressAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
}

#pragma mark==================createUI======================
- (void)createUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.contentInset = UIEdgeInsetsMake(5, 0, 0, 0);
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    [self makeConstraints];
}

- (void)makeConstraints{
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];

}

#pragma mark==================获取地址列表数据======================
- (void)BK_ODAddress_getData_AddressList{
    kOrderLoading;
    __weak typeof(self)weakSelf = self;
    
    if (self.exceptionView) {
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
    
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:kOrderURL(ODAddressList) parameters:nil success:^(id  _Nullable responseObject){
        
        BOOL success = [responseObject[@"success"] boolValue];
        if (!success) {
            kOrderDismiss;
            kOrderPromptMsg(responseObject[@"msg"]);
        }
        if ([responseObject[@"data"] isKindOfClass:[NSArray class]]) {
            NSArray *arr = responseObject[@"data"];
            if (!arr || !arr.count) {
                kOrderDismiss;
            }
            [weakSelf create_SectionModel:[NSArray array]];
            [_tableView reloadData];
            return;
        }
        NSDictionary *data = responseObject[@"data"];
        NSArray *addressList = data[@"list"];

        [weakSelf create_SectionModel:addressList];
        [_tableView reloadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(100 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:_index];
            [_tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            
            
            
        });
        kOrderDismiss;
        
    }failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        kOrderDismiss;
        if (!weakSelf.exceptionView && error) {
            
            ExceptionCodeType codeType;
            if (error.code == -1001) {
                codeType = ExceptionCodeTypeRequestFailed;
            }else{
                codeType = ExceptionCodeTypeServerError;
            }
            
            weakSelf.exceptionView = [ExceptionView exceptionViewWithType:codeType];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:codeType handler:^(ExceptionViewAction *action) {
                [weakSelf BK_ODAddress_getData_AddressList];
            }];
            [weakSelf.exceptionView addAction:action];
            [weakSelf.exceptionView showInView:weakSelf.view];
        }
    }];
}

#pragma mark==================构建SectionModel======================
- (void)create_SectionModel:(NSArray *)dataList{
    
    
    
    
    
    NSMutableArray <SectionModel *> *sectionArr = [NSMutableArray array];
    
    //一个分区一个cell
    if (dataList && dataList.count) {
        NSInteger *index = 0;
        for (NSDictionary *ads in dataList){
            index++;
            BKODDetailsAddressObject *adsObj = [BKODDetailsAddressObject mj_objectWithKeyValues:ads];
            CellModel       *cm = [[CellModel alloc] init];
            cm.className        = NSStringFromClass([BKODAddressCell class]);
            cm.reuseIdentifier  = [NSString stringWithFormat:@"addressCell_%ld",(long)index];
            cm.userInfo         = adsObj;
            cm.delegate         = self;
            cm.height           = [BKODAddressCell computeHeight:adsObj];
            
            SectionModel *sm    = [SectionModel sectionModelWithTitle:@"" cells:@[cm]];
            sm.headerhHeight    = 5;
            sm.footerHeight     = 5;
            [sectionArr addObject:sm];
            
//            /*
//             *  添加完收货地址并选中使用
//             */
//            if ([[BK_Adress_Tool BK_getStr_withID:@"Add_Address_Success_and_Use"] isEqualToString:@"Success"]) {
////                if ((int)index==2) {
////                    _index = 2;
////                    
////                }
////                [self backOrderViewController:[NSIndexPath indexPathForRow:0 inSection:4]];
//                
//            }else{
//                if ([_use_address.deliver_id isEqualToString:adsObj.deliver_id]) {
//                    _index = [sectionArr indexOfObject:sm];
//                }
//            }
//            
            
            
            if ([_use_address.deliver_id isEqualToString:adsObj.deliver_id]) {
                _index = [sectionArr indexOfObject:sm];
            }
            
            
            

        }
    }
//    [BK_Adress_Tool BK_saveStr:@"None" withID:@"Add_Address_Success_and_Use"];
    
    CellModel *addCm        = [[CellModel alloc] init];
    addCm.className         = NSStringFromClass([BKODAddNewAddressCell class]);
    addCm.reuseIdentifier   = @"ODAddAddress_cell";
    addCm.delegate          = self;
    addCm.height            = [BKODAddNewAddressCell computeHeight:nil];
    addCm.userInfo          = @"";
    
    SectionModel *addSm     = [SectionModel sectionModelWithTitle:@"" cells:@[addCm]];
    addSm.headerhHeight     = 5;
    addSm.footerHeight      = 10;
    [sectionArr addObject:addSm];
    
    _marr_Section = sectionArr.copy;
}


//添加收货地址
- (void)addAddressAction:(UIBarButtonItem *)sender{
    [self ODCellAddAddress:nil];
}
/*
 * 添加收货地址
 */
- (void)ODCellAddAddress:(BKODAddNewAddressCell *)cell{
    
    UIViewController *adsVC = [[Mediator sharedInstance] BK_my_ShippingAddressVC:@{@"isAdd" :@"1",@"isCome_OD" :@"1"}];
    adsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:adsVC animated:YES];
}

#pragma mark  table  delegaet && dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return        sm.cells.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel    *cm = sm.cells[indexPath.row];
    
    BK_Confirm_Order_Cell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell){
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.delegate = cm.delegate;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel    *cm = sm.cells[indexPath.row];
    
    BK_Confirm_Order_Cell *ODCell = (BK_Confirm_Order_Cell *)cell;
    
    SEL fillData = @selector(fillData:);
    if ([ODCell respondsToSelector:fillData]) {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        [ODCell performSelector:fillData withObject:cm.userInfo];
        #pragma clang diagnostic pop
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.footerHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel    *cm = sm.cells[indexPath.row];
    
    return cm.height;
}

//点击cell 直接选中返回确认订单
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self backOrderViewController:indexPath];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)backOrderViewController:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel    *cm = sm.cells[indexPath.row];
    
    BKODDetailsAddressObject *adsObj = cm.userInfo;
    
    _use_address.deliver_id = adsObj.deliver_id;
    _use_address.deliver_mobile = adsObj.telephone;
    _use_address.deliver_address = [NSString stringWithFormat:@"%@%@%@%@", adsObj.province_name, adsObj.city_name, adsObj.county_name, adsObj.address];
    _use_address.deliver_name = adsObj.deliver_name;
    if (self.block) {
        self.block(_use_address);
    }
}

#pragma mark  cell delegate
- (void)ODAddressCellEditAddressInfo:(BKODAddressCell *)cell{
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel    *cm = sm.cells[indexPath.row];
    
    BKODDetailsAddressObject *adsObj = cm.userInfo;

    NSMutableDictionary *paramDic = adsObj.mj_keyValues;
    [paramDic setObject:@"0" forKey:@"isAdd"];
    
    UIViewController *adsVC = [[Mediator sharedInstance] BK_my_ShippingAddressVC:paramDic.copy];
    adsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:adsVC animated:YES];
}

@end















































